//
//  HomeTableViewController.m
//  UILabel+tfyAttributeTapAction-Demo
//
//  Created by ltfy on 2018/11/21.
//  Copyright © 2018年 Ltfy. All rights reserved.
//

#import "HomeTableViewController.h"
#import "HomeCell.h"
#import "TFY_CategoryHerder.h"

@interface HomeTableViewController ()
<
TFY_RichTextDelegate
>
@property (nonatomic, strong) NSArray * dataArray;

@property (nonatomic, assign) BOOL isShowTotal;

@end

@implementation HomeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI
{
    self.tableView.tableFooterView = [UIView new];
    self.tableView.sectionHeaderHeight = 30;
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeCell" bundle:nil] forCellReuseIdentifier:HomeCellID];
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

- (void)dealloc
{
    NSLog(@"HomeTableViewController 释放了");
}

#pragma mark - lazyloads
- (NSArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = @[
                       @"点击展开/收起",
                       @"点击的几个字符相同",
                       @"点击的字符不同",
                       @"label上加手势",
                       @"点击的字符字体不一",
                       @"点击的字符不在一行",
                       @"连续跳转",
                       @"没有任何点击效果"
                       ];
    }
    return _dataArray;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, 30)];
    backView.backgroundColor = [UIColor blackColor];
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, self.tableView.bounds.size.width - 30, 30)];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:15];
    label.text = self.dataArray[section];
    [backView addSubview:label];
    
    return backView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HomeCell *cell = [tableView dequeueReusableCellWithIdentifier:HomeCellID forIndexPath:indexPath];
    //框架已经做过处理，点击label会响应cell的点击事件，点击具体的字会响应框架的方法
    if (indexPath.section == 0) {
        cell.testTapLabel.tag = 100;
        NSString * totalText = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"test_1" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];
        totalText = [totalText substringToIndex:totalText.length - 1];//去掉文本最后的一个/n符
        if (self.isShowTotal) {
            NSString * showText = [NSString stringWithFormat:@"%@收起",totalText];
            NSMutableAttributedString * attString = tfy_MutableString(showText);
            attString.tfy_FontName([UIFont systemFontOfSize:15], NSMakeRange(0, showText.length))
            .tfy_ForegroundColorName([UIColor darkGrayColor], NSMakeRange(0, showText.length))
            .tfy_ForegroundColorName([UIColor blueColor], NSMakeRange(showText.length - 2, 2));
            
            cell.testTapLabel.attributedText = attString;
            
            //这里要用delegate，block不好处理，每次都要重新写这个方法，因为attributedText有变动了
            [cell.testTapLabel tfy_addAttributeTapActionWithRanges:@[NSStringFromRange(NSMakeRange(showText.length - 2, 2))] delegate:self];
        }else {
            NSString * showText = [NSString stringWithFormat:@"%@展开",[totalText substringToIndex:80]];
             NSMutableAttributedString * attString = tfy_MutableString(showText);
                       attString.tfy_FontName([UIFont systemFontOfSize:15], NSMakeRange(0, showText.length))
                       .tfy_ForegroundColorName([UIColor darkGrayColor], NSMakeRange(0, showText.length))
                       .tfy_ForegroundColorName([UIColor blueColor], NSMakeRange(showText.length - 2, 2));
           
            
            cell.testTapLabel.attributedText = attString;
            
            [cell.testTapLabel tfy_addAttributeTapActionWithRanges:@[NSStringFromRange(NSMakeRange(showText.length - 2, 2))] delegate:self];
        }
    }else if (indexPath.section == 1) {
        NSString * showText = @"如您有任何疑问，请联系ltfy5834@126.com,\n\n\n\n如您有任何疑问，请联系ltfy5834@126.com,\n\n\n\n\n如您有任何疑问，请联系ltfy5834@126.com";
        cell.testTapLabel.attributedText = [NSAttributedString getAttributeId:@[@"ltfy5834@126.com",@"ltfy5834@126.com",@"ltfy5834@126.com"] string:showText orginFont:15 orginColor:[UIColor darkGrayColor] attributeFont:18 attributeColor:[UIColor blueColor]];
        
        [cell.testTapLabel tfy_addAttributeTapActionWithStrings:@[@"ltfy5834@126.com",@"ltfy5834@126.com",@"ltfy5834@126.com"] tapClicked:^(UILabel *label, NSString *string, NSRange range, NSInteger index) {
            
            NSString * message = [NSString stringWithFormat:@"点击了\"%@\"字符\nrange:%@\n在数组中是第%ld个",string,NSStringFromRange(range),index + 1];
            UIAlertControllerAlertCreate(@"提示", message)
            .addCancelAction(@"确定", 1)
            .addDesAction(@"确定", 2)
            .showFromViewController(self);
        }];
    }else if (indexPath.section == 2) {
        NSString * showText = @"你的快递包裹到了，签收人：张三，电话：13987654321，送货员：李四，电话：15888888888，收件地址：火星";
        cell.testTapLabel.attributedText = [NSAttributedString getAttributeId:@[@"13987654321",@"15888888888"] string:showText orginFont:15 orginColor:[UIColor darkGrayColor] attributeFont:15 attributeColor:[UIColor blueColor]];
        
        [cell.testTapLabel tfy_addAttributeTapActionWithStrings:@[@"13987654321",@"15888888888"] tapClicked:^(UILabel *label, NSString *string, NSRange range, NSInteger index) {
            
            NSString * message = [NSString stringWithFormat:@"点击了\"%@\"字符\nrange:%@\n在数组中是第%ld个",string,NSStringFromRange(range),index + 1];
             UIAlertControllerAlertCreate(@"提示", message)
                       .addCancelAction(@"确定", 1)
                       .addDesAction(@"确定", 2)
                       .showFromViewController(self);
        }];
    }else if (indexPath.section == 3) {
        NSString * showText = @"点击红色字体会走代理方法，测试点击，点label会响应手势事件，查看控制台输出";//手势比较特别，会同时响应框架代理和手势方法
        cell.testTapLabel.attributedText = [NSAttributedString getAttributeId:@[@"测试点击"] string:showText orginFont:15 orginColor:[UIColor darkGrayColor] attributeFont:15 attributeColor:[UIColor redColor]];
        cell.testTapLabel.tag = 200;
        [cell.testTapLabel tfy_addAttributeTapActionWithStrings:@[@"测试点击"] delegate:self];
        
        UITapGestureRecognizer * tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTestGestureRecognizerAction:)];
        cell.testTapLabel.userInteractionEnabled = YES;
        [cell.testTapLabel addGestureRecognizer:tapGes];
    }else if (indexPath.section == 4) {
        NSString * showText = @"恭喜您获得了一张￥50优惠券，赶快去钱包看看并下单使用吧~";
        NSMutableAttributedString * attString = tfy_MutableString(showText);
        attString.tfy_FontName([UIFont systemFontOfSize:15], NSMakeRange(0, showText.length))
        .tfy_ForegroundColorName([UIColor darkGrayColor], NSMakeRange(0, showText.length))
        .tfy_FontName([UIFont systemFontOfSize:13], NSMakeRange(8, 1))
        .tfy_FontName([UIFont systemFontOfSize:22], NSMakeRange(9, 2))
        .tfy_ForegroundColorName([UIColor redColor], NSMakeRange(8, 3));
        
        cell.testTapLabel.attributedText = attString;
        
        [cell.testTapLabel tfy_addAttributeTapActionWithStrings:@[@"￥50"] tapClicked:^(UILabel *label, NSString *string, NSRange range, NSInteger index) {
            NSString * message = [NSString stringWithFormat:@"点击了\"%@\"字符\nrange:%@\n在数组中是第%ld个",string,NSStringFromRange(range),index + 1];
             UIAlertControllerAlertCreate(@"提示", message)
                       .addCancelAction(@"确定", 1)
                       .addDesAction(@"确定", 2)
                       .showFromViewController(self);
        }];
    }else if (indexPath.section == 5) {
        NSString * showText = @"\nWe are committed to providing quality services to you.  Our privacy policy outlines our ongoing obligations to you in respect of how we manage your personal information.\nThis policy may change from time to time in order to ensure we fully comply with the latest laws and regulations relative to our services.\nhttps://www.breville.com/au/en/legal/privacy-policy.html\nBy clicking AGREE, you agree below that you have fully read, understood and accepted the privacy policy in its entirety.  If you have any queries, please contact us at any time. \nAnd for your convenience, we direct you to Amazon Web Services’ privacy policy which applies to information you provide to them.\nhttps://aws.amazon.com/privacy/\n";
        cell.testTapLabel.attributedText = [NSAttributedString getAttributeId:@[@"https://www.breville.com/au/en/legal/privacy-policy.html",@"https://aws.amazon.com/privacy/"] string:showText orginFont:15 orginColor:[UIColor darkGrayColor] attributeFont:15 attributeColor:[UIColor blueColor]];
        
        [cell.testTapLabel tfy_addAttributeTapActionWithStrings:@[@"https://www.breville.com/au/en/legal/privacy-policy.html",@"https://aws.amazon.com/privacy/"] tapClicked:^(UILabel *label, NSString *string, NSRange range, NSInteger index) {
            NSString * message = [NSString stringWithFormat:@"点击了\"%@\"字符\nrange:%@\n在数组中是第%ld个",string,NSStringFromRange(range),index + 1];
             UIAlertControllerAlertCreate(@"提示", message)
                       .addCancelAction(@"确定", 1)
                       .addDesAction(@"确定", 2)
                       .showFromViewController(self);
        }];
    }else if (indexPath.section == 6) {
        NSString * showText = @"点击\"点我跳下一页\"进入下一页";
        cell.testTapLabel.attributedText = [NSAttributedString getAttributeId:@[@"\"点我跳下一页\""] string:showText orginFont:15 orginColor:[UIColor darkGrayColor] attributeFont:15 attributeColor:[UIColor blueColor]];
        cell.testTapLabel.tag = 300;
        [cell.testTapLabel tfy_addAttributeTapActionWithStrings:@[@"\"点我跳下一页\""] delegate:self];
    }else {
        NSString * showText = @"此label没有附加任何点击效果\n调用\"tfy_removeAttributeTapActions\"方法是为了防止cell复用后，label上还有点击事件";
        cell.testTapLabel.attributedText = [NSAttributedString getAttributeId:@"tfy_removeAttributeTapActions" string:showText orginFont:15 orginColor:[UIColor darkGrayColor] attributeFont:15 attributeColor:[UIColor redColor]];
        [cell.testTapLabel tfy_removeAttributeTapActions];
    }
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section != self.dataArray.count - 1) {
        return nil;
    }
    static NSString * identifier = @"footerView";
    UITableViewHeaderFooterView * footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identifier];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:identifier];
        __block UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(15, 10, [UIScreen mainScreen].bounds.size.width - 30 , 60)];
        footerView.contentView.backgroundColor = [UIColor yellowColor];
        [button setImage:[UIImage imageNamed:@"btn_unSel"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"btn_sel"] forState:UIControlStateSelected];
        [button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 34, 0)];
        [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
        NSString * showText = @"您已阅读并同意《用户注册协议》《用户使用协议》《用户保密协议》《平台使用守则》《平台免责申明》《网络安全协议》";
        NSAttributedString * showAttString = [NSAttributedString getAttributeId:@[@"《用户注册协议》",@"《用户使用协议》",@"《用户保密协议》",@"《平台使用守则》",@"《平台免责申明》",@"《网络安全协议》"] string:showText orginFont:15 orginColor:[UIColor darkGrayColor] attributeFont:15 attributeColor:[UIColor blueColor]];
        [button setAttributedTitle:showAttString forState:UIControlStateNormal];
        button.titleLabel.numberOfLines = 0;
        [footerView.contentView addSubview:button];
        [button addTarget:self action:@selector(onButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
        [button.titleLabel tfy_addAttributeTapActionWithStrings:@[@"您已阅读并同意",@"《用户注册协议》",@"《用户使用协议》",@"《用户保密协议》",@"《平台使用守则》",@"《平台免责申明》",@"《网络安全协议》"] tapClicked:^(UILabel *label, NSString *string, NSRange range, NSInteger index) {
            
            if ([string isEqualToString:@"您已阅读并同意"]) {
                button.selected = !button.selected;
            }else {
                NSString * message = [NSString stringWithFormat:@"点击了\"%@\"字符\nrange:%@\n在数组中是第%ld个",string,NSStringFromRange(range),index + 1];
                UIAlertControllerAlertCreate(@"提示", message)
                           .addCancelAction(@"确定", 1)
                           .addDesAction(@"确定", 2)
                           .showFromViewController(self);
            }
            
        }];
    }
    
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section != self.dataArray.count - 1) {
        return 0;
    }
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击了cell");
}

#pragma mark - action
- (void)onButtonClickAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
}

#pragma mark - tfyAttributeTapActionDelegate
- (void)tfy_tapAttributeInLabel:(UILabel *)label string:(NSString *)string range:(NSRange)range index:(NSInteger)index
{
    if (label.tag == 100) {
        self.isShowTotal = !self.isShowTotal;
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    }else if (label.tag == 200) {
        NSString * message = [NSString stringWithFormat:@"点击了\"%@\"字符\nrange:%@\n在数组中是第%ld个",string,NSStringFromRange(range),index + 1];
         UIAlertControllerAlertCreate(@"提示", message)
                   .addCancelAction(@"确定", 1)
                   .addDesAction(@"确定", 2)
                   .showFromViewController(self);
    }else if (label.tag == 300) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - func
- (void)onTestGestureRecognizerAction:(UITapGestureRecognizer *)tapGes
{
    NSLog(@"点击了手势事件");
}

@end
